<template>
	<view class="userinfo" :style="{marginTop:systemBarHeight+'px'}">
		<view class="header">
			<image src="../../static/images/commom/back.png" class="btn back" @tap="back"></image>
			<view class="text">
				详细
			</view>
		</view>
		<view class="container" :style="{top:(systemBarHeight+60)+'px'}">
			<view class="info head">
				<view class="text">
					头像
				</view>
				<view class="middle">
					<!-- <image src="../../static/images/userimg/pic_d.jpg" class="img"></image> -->
					<image-cropper :src="tempFilePath" @confirm="confirm"  @cancel="cancel"></image-cropper>				
					<image :src="cropFilePath" @tap="upload" class="img meslist_img"></image>
				</view>
			</view>
			<view class="info">
				<view class="text">
					签名
				</view>
				<view class="middle">
					{{qianming}}
				</view>
				<image src="../../static/images/commom/right.png" class="img right" 
				v-if="isfriend == 0"
				@tap="openchange('签名')"></image>
			</view>
			<view class="info baseline">
				<view class="text">
					注册
				</view>
				<view class="middle">
					{{createtime}}
				</view>
			</view>
			<view class="info">
				<view class="text">
					昵称
				</view>
				<view class="middle">
					{{niki}}
				</view>
				<image src="../../static/images/commom/right.png" class="img right"
				v-if="isfriend == 0 ? true : isfriend == 1 ? true : false"
				@tap="openchange('昵称')"></image>
			</view>
			<view class="info">
				<view class="text">
					性别
				</view>
				 <picker @change="bindPickerChange" :value="index" :range="array" v-if="isfriend == 0">
					<view class="middle uni-input">{{array[index]}}</view>
				</picker>
				<view class="middle" v-if="isfriend != 0">
					{{array[index]}}
				</view>
				<!-- <image src="../../static/images/commom/right.png" class="img right"></image> -->
			</view>
			<view class="info">
				<view class="text">
					生日
				</view>
				<picker mode="date" :value="date" :start="startDate" :end="endDate" @change="bindDateChange"  v-if="isfriend == 0">
					<view class="middle uni-input">{{date}}</view>
				</picker>
				<view class="middle" v-if="isfriend != 0">
					{{date}}
				</view>
				<!-- <image src="../../static/images/commom/right.png" class="img right"></image> -->
			</view>
			<view class="info">
				<view class="text">
					电话
				</view>
				<view class="middle">
					{{tel}}
				</view>
				<image src="../../static/images/commom/right.png" class="img right"
				v-if="isfriend == 0"
				@tap="openchange('电话')"></image>
			</view>
			<view class="info baseline">
				<view class="text">
					邮箱
				</view>
				<view class="middle">
					{{email}}
				</view>
				<image src="../../static/images/commom/right.png" class="img right"
				v-if="isfriend == 0"
				@tap="openchange('邮箱')"></image>
			</view>
			<view class="info" v-if="isfriend == 0">
				<view class="text">
					密码
				</view>
				<view class="middle">
					************
				</view>
				<image src="../../static/images/commom/right.png" class="img right"
				@tap="openchange('密码')"></image>
			</view>
		</view>
		<view class="bottom">
			<view class="box out" v-if="isfriend == 0" @tap="accountout">
				退出登录
			</view>
			<view class="box chartroom" v-if="isfriend == 1" @tap="deletefriend">
				删除好友
			</view>
			<view class="box addfriend" v-if="isfriend == 2" @tap="addfriend">
				加为好友
			</view>
		</view>
		<transition name="fade">
			<infochange v-show="changeflag" 
			:title = "title"
			:value = "value"
			:flag = "pswflag"
			@close = "close"
			@decide = "decide"></infochange>
		</transition>
	</view>
</template>

<script>
	import ImageCropper from "@/components/ling-imgcropper/ling-imgcropper.vue";
	import infochange from "../../components/infochange/infochange.vue"
	export default {
		data() {
			const currentDate = this.getDate({
				format: true
			})
			return {
				user:{},
				changeflag:false,
				title:'',
				qianming:'',
				fid:'',
				niki:"",
				tel:'',
				email:'',
				psw:'',
				value:'',
				pswflag:false,
				array: ['男', '女','未知'],
				createtime:'0000-00-00',//账号的创建时间
				isfriend:'',//0为本人，1为好友，2为不是好友
				index: 0,//选择性别的定位数
				date: currentDate,//选择生日，默认为0000-00-00
				tempFilePath: "",
				cropFilePath: "",
				systemBarHeight:''
			};
		},
		onLoad(e){
			this.getSysteminfo();
			this.fid = e.id;
			this._gettoken();
			this._getuserdetail();
		},
		computed: {
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		methods:{
			getSysteminfo() {//获取系统栏高度
				uni.getSystemInfo({
					success: (res) => {
						this.systemBarHeight = res.statusBarHeight;
					}
				});
			},
			accountout(){//退出登录
				uni.navigateTo({
					url:"../llogin/llogin"
				})
			},
			deletefriend(){//删除好友
				let uid = this.user.id;
				let fid = this.fid;
				uni.request({
					url:this.serverurl+"friend/deletefriend",
					data:{
						uid,
						fid,
						token:this.user.token,
					},
					method:'POST',
					success:(res)=>{
						let info = res.data;
						if(info.status == 200){
							uni.navigateTo({
								url:`../friendslist/friendslist?del=1`
							})
						} 
						else if(info.status == 300){
							uni.navigateTo({//token过期
								url:"../llogin/llogin?name="+this.user.name
							})
						}else{
							uni.showToast({
							    title:'删除失败',
							    duration: 2000,
							    icon:'none',
							    position:'top'
							});
						}
						
					}
				})
			},
			addfriend(){//添加好友
				let uid = this.user.id;
				let fid = this.fid;
				uni.request({
					url:this.serverurl+"friend/applyfriend",
					data:{
						uid,
						fid,
						token:this.user.token,
						message:`${this.user.name}向${this.niki}发出好友的申请`
					},
					method:'POST',
					success:(res)=>{
						let info = res.data;
						if(info.status == 200){
							uni.showToast({
							    title:'申请消息发送',
							    duration: 2000,
							    icon:'none',
							    position:'top'
							});
						}
						else if(info.status == 300){
							uni.navigateTo({//token过期
								url:"../llogin/llogin?name="+this.user.name
							})
						}else{
							uni.showToast({
							    title:'发送失败',
							    duration: 2000,
							    icon:'none',
							    position:'top'
							});
						}
						
					}
				})
			},
			_gettoken(){//获取缓存数据token值和id值
				try {
				    const value = uni.getStorageSync('wikiuser');
				    if (value) {
				        this.user = JSON.parse(value)
				    }
				} catch (e) {
				    console.log(e)
				}
			},
			_getuserdetail(){//通过uid,fid获取用户的详情信息
				uni.request({
					url:this.serverurl+"user/detail",
					data:{
						uid:this.user.id,
						fid:this.fid,
						token:this.user.token
					},
					method:'POST',
					success:(result)=>{
						let info = result.data;
						if(info.status == 200){
							let obj = info.data;
							this.qianming = obj.desc;
							this.niki = obj.markname;
							if(typeof(obj.tel) == 'undefined'){
								this.tel = "000000000"
							}else{
								this.tel = obj.tel
							}
							console.log(obj.birthday)
							if(typeof(obj.birthday)=='undefined'){
								this.date = "0000-00-00"
							}else{
								this.date = obj.birthday
							}
							this.email = obj.email;
							this.index = this._choosesex(obj.sex);//选择性别
							this.createtime = obj.time;//赋值账号的创建时间
							this.cropFilePath = this.serverurl+`userimage/${obj.imgurl}`;
							this.isfriend = obj.isfriend;//判断是否为好友
							// this.psw = obj.psw;//用户的密码信息
						}
					}
				})
			},
			_choosesex(info){
				if(info === 'male'){
					return 0;
				}else if(info == 'female'){
					return 1;
				}else{
					return 2;
				}
			},
			back(){//返回按钮
				uni.navigateBack({
					delta:1
				})
			},
			bindDateChange: function(e) {
				this.date = e.target.value
				this._updatainfo(undefined,'birthday',this.date).then((data)=>{
					
				})
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
	
				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			bindPickerChange: function(e) {
				// console.log('picker发送选择改变，携带值为', e.target.value)
				this.index = e.target.value;
				let result = this.index == 0 ? 'male' : this.index == 1 ? 'female' : 'unknow';
				this._updatainfo(undefined,'sex',result).then((data)=>{
					
				})
			},
			openchange(title){		//打开修改界面		
				this.title = title;
				if(title === "签名"){
					this.value = this.qianming
				}else if(title === "昵称"){
					this.value = this.niki
				}else if(title === "电话"){
					this.value = this.tel
				}else if(title === "邮箱"){
					this.value = this.email;
					this.pswflag = true;
					
				}else if(title === "密码"){
					this.pswflag = true;
					this.value = '';
				}
				this.changeflag = true;
			},
			close(flag){
				this.changeflag = flag;
				this.pswflag = false;
				this.psw = '';
				this.value = '';
			},
			_changemarkname(name){//更改昵称
				uni.request({
					url:this.serverurl+"user/updatemarkname",
					data:{
						uid:this.user.id,
						fid:this.fid,
						markname:name,
						token:this.user.token
					},
					method:'POST',
					success: (result) => {
						let info = result.data;
						if(info.status == 200){
							uni.showToast({
							    title:'昵称修改成功',
							    duration: 2000,
							    icon:'none',
							    position:'top'
							});
							this.niki = name
						}else if(info.status == 500){
							uni.showToast({
							    title:'昵称修改失败',
							    duration: 2000,
							    icon:'none',
							    position:'top'
							});
						}else if(info.status == 300){
							uni.navigateTo({//token过期
								url:"../llogin/llogin?name="+this.user.name
							})
						}
					}
				})
			},
			decide(title,text,psw){
				if(title === "签名"){
					this._updatainfo(undefined,'desc',text).then((data)=>{
						this.qianming = data;
					})
				}else if(title === "昵称"){
					if(this.user.id != this.fid){
						this._changemarkname(text);//修改昵称
					}else{
						this._updatainfo(undefined,'name',text).then((data)=>{
							this.niki = data;
						})
					}
				}else if(title === "电话"){
					this._updatainfo(undefined,'tel',text).then((data)=>{
						this.tel = data;
					})
				}else if(title === "邮箱"){
					if(text == ""){
						uni.showToast({
							title:'邮箱不可为空',
							duration: 2000,
							icon:'none',
							position:'top'
						});
						return;
					}
					let emailrexg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
					if(!emailrexg.test(text)){
						uni.showToast({
							title:'邮箱格式错误',
							duration: 2000,
							icon:'none',
							position:'top'
						});
					}else{
						if(psw == ""){
							uni.showToast({
								title:'请输入密码验证',
								duration: 2000,
								icon:'none',
								position:'top'
							});
							return;
						}
						this._updatainfo(psw,'email',text).then((data)=>{
							this.email = data;
						})
					}	
				}else if(title === "密码"){
					if(text == ""){
						uni.showToast({
							title:'新密码不可为空',
							duration: 2000,
							icon:'none',
							position:'top'
						});
						return;
					}				
					this._updatainfo(psw,'psw',text).then((data)=>{
						try {
						    uni.removeStorageSync('wikiuser');
						} catch (e) {
						    
						}
						uni.navigateTo({
							url:"../llogin/llogin?psw=1"
						})
					})
				}
			},
			upload() {
				if(this.isfriend != 0){//如果不是本人不允许更换头像
					return;
				}
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						this.tempFilePath = res.tempFilePaths.shift()
					}
				});
			},
			confirm(e) {
				this.tempFilePath = ''
				this.cropFilePath = e.detail.tempFilePath
				uni.uploadFile({
					url: this.serverurl+'files/upload',
					filePath: this.cropFilePath,
					name: "file",
					fileType: "image",
					formData: {
					    'user': 'wiki',
						'url':'userimage',
						'name':this.fid,
					},
					success: (uploadFileRes) => {
					  var backstr = JSON.parse(uploadFileRes.data);
					  this._updatainfo(undefined,'imgurl',backstr.filename).then((data)=>{
						  console.log(data)
					  })
					},
					fail(e) {
					  // console.log("this is errormes " + e.message);
					},
				  });
			},
			cancel() {
				// console.log('canceled')
			},
			_updatainfo(pwd,type,data){//修改用户信息			
				return new Promise((resolve,reject)=>{				
					uni.request({
						url:this.serverurl+"user/update",
						data:{
							id:this.fid,
							pwd,
							type,
							data
						},
						method:'POST',
						success: (result) => {
							let info = result.data;
							if(info.status == 200){
									uni.showToast({
										title:'修改成功',
										duration: 2000,
										icon:'none',
										position:'top'
									});
									this.close();
								resolve(data)							
								}else if(info.status == 500){
									uni.showToast({
										title:'网络错误',
										duration: 2000,
										icon:'none',
										position:'top'
									});
								}else if(info.status == 600){
									uni.showToast({
										title:'邮箱重复',
										duration: 2000,
										icon:'none',
										position:'top'
									});
								}
								else if(info.status == 100){
									uni.showToast({
										title:'密码错误',
										duration: 2000,
										icon:'none',
										position:'top'
									});
								}
								else if(info.status == 400){
									uni.showToast({
										title:'用户信息错误',
										duration: 2000,
										icon:'none',
										position:'top'
									});
									}
								else if(info.status == 300){
								uni.navigateTo({//token过期
									url:"../llogin/llogin?name="+this.user.name
								})
							}
						}
					})			
				})	
			}
		},
		components:{
			ImageCropper,
			infochange
		}
	}
</script>

<style lang="scss">
.userinfo{
	position: fixed;
	top: 0;
	bottom: 0;
	width: 100%;
	.header{
		position: absolute;
		height: 120rpx;
		width: 100%;
		padding: 0 42rpx;		
		box-sizing: border-box;
		border-bottom: 1px solid rgba(187, 187, 187, 100);;
		.btn{
			position: absolute;
			top: 50%;
			transform: translateY(-50%);
			width: 48rpx;
			height: 48rpx;		
		}
		.text{
			flex: 1;
			text-align: center;
			line-height: 120rpx;
			color: rgba(16, 16, 16, 100);
			font-size: 48rpx;
			// font-weight: bold;
		}
	}
	.container{
		position: fixed;
		top: 120rpx;
		bottom: 0;
		width: 100%;
		padding: 48rpx 36rpx;
		box-sizing: border-box;
		.info{
			height: 130rpx;
			box-sizing: border-box;
			width: 100%;
			padding: 24rpx 0;
			display: flex;
			align-items: center;
			&.baseline{
				border-bottom: 2rpx solid rgba(187, 187, 187, 100);
			}
			.text{
				color: rgba(16, 16, 16, 100);
				font-size: 28rpx;
				width: 80rpx;
				flex: 0 0 80rpx;
			}
			.middle{
				flex: 1;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				color: rgba(158, 158, 158, 100);
				font-size: 28rpx;
				.img{
					box-sizing: border-box;
					width: 88rpx;
					height: 88rpx;
					border-radius: 14rpx;
					border: 4rpx solid rgba(52, 199, 88, 100);
				}
			}
			.right{
				width: 48rpx;
				height: 48rpx;
				flex: 0 0 48rpx;
			}
		}
	}
	.bottom{
		position: absolute;
		bottom: 120rpx;
		width: 100%;
		.box{
			width: 30%;
			height: 80rpx;
			margin: 0 auto;
			text-align: center;
			line-height: 80rpx;
			font-size: 44rpx;
			&.out{
				color: rgba(252,85,49,1);
			}
			&.chartroom{
				color: rgba(252,85,49,1);
			}
			&.addfriend{
				color: rgba(72,143,199,1);
			}
		}
		
	}
	.fade-enter-active, .fade-leave-active {
	  transition: opacity .5s;
	}
	.fade-enter, .fade-leave-to  {
	  opacity: 0;
	}
}
</style>
